#!/usr/bin/python
# Sample console application serving as a sensor data
# receiver and distributor. Runs the data through a
# predefined filter chain

import sys, time
from Sensor import Sensor

scale = { "x" : 1./330, "y" : 1./330, "z": 1./330 }
def normalize(block):
    "sample filter: normalize to -1..1 cube on the basis of scale"
    packet = block[0] # just the first
    for key in packet:
        if key in scale:
            packet[key] = packet[key]*scale[key] # in place edit fine
    return block 

def show_packet(packet, msg=""):
    "sample sink: simple display"
    if msg:
        print "%s: %s" % (msg, str(packet))
    else:
        print packet


if __name__ == '__main__':
    print "  -v verbose, -r record, -i serve forever, -b bluetooth"
    serve_time = 600
    if "-b" in sys.argv:
        sensor = Sensor(17) # bluetooth port
    else:
        sensor = Sensor() # standard port, UDP
    sensor.register_filter(normalize) # register filter
    if "-v" in sys.argv: # verbose, register echo sink
        sensor.register_sink(show_packet)
        sensor.register_rawsink(lambda x: show_packet(x, "raw"))
    if "-r" in sys.argv: # record
        sensor.reg_record()
    if "-i" in sys.argv: # serve until interrupted
        serve_time = 2**30 # well, long enough
    sensor.reg_send() # register sink sending final packet[0] to def. port
    # receive and distribute for 10 minutes
    sensor.start_receiving()
    try:
        time.sleep(serve_time)
        print "reached time limit"
    except KeyboardInterrupt:
        print "ignoring exception" # ignore, Ctrl-C
    sensor.stop_receiving()
    sensor.unreg_record()
